// var xss = require('xss');
import fs from 'fs-extra';
import path from 'path';
import base64 from 'base-64';
import Markdown from '../modules/markdown';
import Config from '../conf';
import mdPage from '../views/mdPage';
import parseSummary from '../modules/parseSummary';
import { simpleTemplate, getVersion } from '../modules';

export default async function MarkdownPage(cx, next) {

	let dirn = cx.path.match(/^\/([^\/]+)/i);
	let book = [];
	if (dirn) {
		book = await cx.locServe.books.find({dirname: dirn[1]}); 
	}
	if (!book.length) {
		await next();
		return;
	}

	// isMdpage区分是否是纯markdown，防止与旧版路由重复
	if (cx.method.toLowerCase() === 'get' && book[0].isMdpage === '1') {
		if (/^\/[^\/]+\/?$/i.test(cx.path)) {
			return cx.response.redirect(path.join(cx.path, '1.0.0/'));
		}
		const urlpath = resolvePath(cx.path);
		const dirname = urlpath.dirname;
		const version = urlpath.version;
		const filepath = urlpath.filepath;
		if (filepath==='') {
			return cx.response.redirect(cx.path+'/');
		}
		const uploadedDir = Config.upload.uploadedDir;
		const prepath = `/${dirname}/${version}/`;
		const realpath = path.join(process.cwd(), uploadedDir, path.join(cx.path, filepath===''||filepath==='/'?'README.md':''));
		if (!fs.existsSync(realpath.replace(/html?$/i,'md'))) {
			return await next();
		}
		const _dirname = path.join(process.cwd(), uploadedDir, dirname);
		
		let versionDir = path.join(_dirname, version);
		let markdownHtm = resolveMardown(markdownPath(realpath));
		let bookjson = parseBookjson(path.join(versionDir, 'book.json'));
		let navs = JSON.parse(parseSummary(path.join(versionDir, 'SUMMARY.md'), prepath));
		let nav = navs.map(function(n){
        var name=unescape(n.name);
        var mathref=unescape(n.value).match(/href=(["'])(.+?)\1/);
        return '<li class="navitem dib" data-subs="'+(n.hasChild?n.id:'')+'">'+ (n.hasChild?'<a href="'+(mathref?mathref[2]:'#')+'">'+name+'</a>':name) +'</li>';
    }).join('');
    let slide = renderSlide(navs, cx);
		let htm = simpleTemplate(mdPage, {
			Title: bookjson.name || bookjson.title,
			Description: bookjson.description,
			Author:bookjson.author,
			Favicon:bookjson.favicon,
			Logo: `${(bookjson.logo&&!/^(https?:)?\/\//.test(bookjson.logo)?prepath:'') + bookjson.logo}`,
			Versions: getVersion(_dirname).map(v => `<option ${version === v? 'selected': ''} value="${v}">${v}</option>`).join(''),
			Navs: nav, 
			NavsData: JSON.stringify(navs),
			Aside: slide,
			Noslide: slide? '':'noslide',
			Article: markdownHtm === '404md'? '你访问的页面不存在哦！': markdownHtm.replace(/\.md/gi,'.html')
		});
		cx.body=htm;
	}else{
		await next();
	}
}
function renderSlide(navs, cx){
	let id;
	for(var i=0;i<navs.length;i++){
    var subs=navs[i];
    if (~unescape(subs.value).indexOf(cx.path)) {
        id = subs.id;
        break;
    }
	}
	let slide = navs.filter(function(n){
		      return n.id == id;
		    });
  return unescape(slide.length?slide[0].value:'');
}


function resolveMardown(markdown){
	let htm = '404md';
	let cachePath = markdown.replace(/\.md$/,'.cache');
	let hasCache = fs.existsSync(cachePath);
	if (hasCache) {
		htm = fs.readFileSync(cachePath, 'utf8');
	}else{
		const exists = fs.existsSync(markdown);
		if (exists) {
			htm = Markdown.render(fs.readFileSync(markdown,'utf8'));
			process.nextTick(() => {
				fs.writeFile(cachePath, htm);
			});
		}
	}
	return htm;
}
function resolvePath(urlpath){
	const matchedPath = urlpath.match(/^\/([^\/]+)\/([^\/]+)(.*)/i);
	return !matchedPath?
			null:
			{
				dirname:matchedPath[1],
				version:matchedPath[2],
				filepath:matchedPath[3]
			}	
}
function isHtmlFile(urlpath){
	return /\.html?$/i.test(urlpath);
}
function markdownPath(urlpath){
	return isHtmlFile(urlpath)?urlpath.replace(/html?$/i,'md'):urlpath//path.join(urlpath,'README.md');
}
function parseBookjson(bookjson) {
	try{
		bookjson = JSON.parse(fs.readFileSync(bookjson,'utf8'));
	}catch(e){
		bookjson = {};
	}
	return bookjson;
}


